<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserRequest;
use App\Http\Resources\Api\UserResource;
use App\Jobs\Api\SaveLastTokenJob;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;


class UserController extends Controller
{
    public function index(){
        $users = User::paginate(3);
        return  api()->success('查找成功',UserResource::collection($users));
    }

    public function show(User $user){
        return  api()->success('查找成功',new UserResource($user));
    }

    public function store(UserRequest $request){
        User::create($request->all());
        return api()->success('用户注册成功');
    }

    public function login(Request $request){
        $token=Auth::attempt(['name'=>$request->name,'password'=>$request->password]);
        if ($token){
            $user = Auth::user();
            if ($user->last_token){
                try {
                    Auth::setToken($user->last_token)->invalidate();
                }catch (TokenExpiredException $e){

                }
            }
            SaveLastTokenJob::dispatch($user,$token);
            return api()->success('用户登录成功',['token' => 'bearer ' . $token]);
        }
           return api()->error(400,'账号或密码错误',400);

    }

    public function logout(){
        Auth::logout();
        return api()->success('推出成功...');
    }

    public function info(){
        $user = Auth::user();
        return api()->success(new UserResource($user));
    }
}
